<script setup>
import { useDictItems } from '@/composables/sys/dict.js'
import {computed} from "vue";

const props = defineProps({
  code: {
    type: String,
    required: true
  },
  value: {
    type: [String, Number],
    default: undefined
  },
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  clearable: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:value'])

// 获取字典项
const { data, isLoading } = useDictItems(props.code)

const options = computed(() => {
  return data.value?.data?.map(item => ({ label: item.label, value: item.value })) || []
})

const displayText = computed(() => {
  const selectedItem = options.value.find(item => item.value === props.value)
  return selectedItem ? selectedItem.label : ''
})
</script>

<template>
  <div>
    <n-select
        v-if="!disabled"
        :value="value"
        :disabled="disabled || isLoading"
        :placeholder="placeholder"
        :clearable="clearable"
        :options="options"
        @update:value="(val) => emits('update:value', val)"
    />
    <span v-else>{{displayText}}</span>
  </div>

</template>

<style scoped>

</style>